import _ from 'lodash'
import axios from '@/utils/axios'
import { getUserInfo } from 'api'

const USER = {
  SET_USER: 'SET_USER',
  SUPPLIERS: 'SUPPLIERS'
}

const initialState = {
  user: {
    companyName: ''
  },
  suppliers: {}
}

const mutations = {
  [USER.SET_USER] (state, user) {
    state.user = user
  },
  [USER.SUPPLIERS] (state, suppliers) {
    state.suppliers = suppliers
  }
}

const actions = {
  changeUserInfo ({ commit }, payload) {
    commit(USER.SET_USER, payload)
  },
  changeSuppliers ({ commit }, payload) {
    commit(USER.SUPPLIERS, payload)
  },
  loadUserInfo ({ commit, dispatch }, {next, to}) {
    return new Promise(async (resolve, reject) => {
      try {
        const { ResultSet } = await axios.post(getUserInfo)
        await dispatch('getDropdownList')
        dispatch('changeUserInfo', ResultSet.Result[0])
        resolve(ResultSet.Result[0])
        next()
      } catch (err) {
        console.log(err)
      }
    })
  }
}

const getters = {
  name (state) {
    return !!state.user.companyName
  }
}

export default {
  state: _.cloneDeep(initialState),
  mutations,
  actions,
  getters
}
